#define _CRT_SECURE_NO_WARNING 1
#include<stdio.h>

void Swap(int* a,int* b)
{
	int tem = *a;
	*a = *b;
	*b = tem;
}


void Adjustdown(int* arr, int size,int parent)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child+1<size && arr[child + 1] < arr[child])
		{
			child++;
		}
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void Heapsort(int* arr, int size)
{
	int i = (size - 2) / 2;
	for (i; i >= 0; i--)
	{
		Adjustdown(arr, size,i);
	}
	for (i = size - 1; i >0; i--)
	{
		Swap(&arr[0],&arr[i]);
		Adjustdown(arr, i -1,0);
	}
}

int main()
{
	int arr[10] = { 8,5,7,13,54,63,1,2,3,87 };
	int i = 0;
	Heapsort(arr, 10);
	for(i;i<10;i++)
	{
		printf("%d ",arr[i]);
	}
	
	return 0;
}
